Home > Enterprise >  How to call template operator?
How to call template operator?

Time:03-26

How can I call declared operator of the class as following code;

class CChQuAuth
{
    public:
        CChQuAuth()
        {
        }
};

class CChQuCached
{
    public:
        CChQuCached()
        {
        }

        template <typename  _ChClass>
        operator bool();
};

template <typename  _ChClass>
CChQuCached::operator bool()
{
    return true;
}

int main()
{
    CChQuCached ChQuCached;

    ChQuCached.operator bool<CChQuAuth>(); // compile error !
}

I got compile error with VS22.

to solve thanks for your help...

CodePudding user response:

There is no direct way

There is no syntax to form a template-id ([temp.names]) by providing an explicit template argument list ([temp.arg.explicit]) for a conversion function template

But there are options to choose from.

  1. Use a general member-function template instead. That's how std::tuple works.
  2. Create own template type convertible to bool. Define conversion operator to that type.
  3. Consider that you actually should do something else. Perhaps visitor pattern is what you're looking for.

Using a default template argument for a template conversion function to a non-template type OR using a template-id as target for conversion function are ONLY ways how one can pass a template-argument while instantiating and invoking said conversion function. E.g.:

class CChQuAuth {
    public:
        CChQuAuth() { }
};

template <typename  T>
struct MyBool {
   bool v; 
   operator bool() { return v;};
}; 

class CChQuCached {
    public:
        CChQuCached() {
        }

       template <typename T>
       operator typename ::MyBool<T>();  
};

template <typename  T>
CChQuCached::operator typename ::MyBool<T>()
{
    return MyBool<T>();
}

int main()
{
    CChQuCached ChQuCached;

    bool b = ChQuCached.operator MyBool<CChQuAuth>();
}

That's just an example and no way a proper boilerplate code. Note that conversion operator name expected to be a nested type-id first, and in this case it is given as fully qualified one, with ::.

CodePudding user response:

Your best bet is to make it a regular function:

struct Type {
    template <typename T>
    bool to_bool() const {
        return true;
    }
};

int main() {
    Type var;
    var.to_bool<char>();
}
  •  Tags:  
  • c
  • Related