C++ 使用运算符()将typename作为参数传递
考虑以下代码:C++ 使用运算符()将typename作为参数传递,c++,templates,operator-overloading,C++,Templates,Operator Overloading,考虑以下代码: struct S { ... template<typename T> T operator() { ... } }; 相反?将类型存储在模板化标记类型结构中: template<class T> struct tag_t { }; template<class T> tag_t<T> tag{}; struct S { template<class T> T
struct S {
...
template<typename T>
T operator() {
...
}
};
相反?将类型存储在模板化标记类型结构中:
template<class T> struct tag_t { };
template<class T> tag_t<T> tag{};
struct S {
template<class T>
T operator()( tag_t<T> );
} s;
s( tag<Foo> );
那么:
struct S {
template<class T>
void operator()(const T&) { }
} s;
struct Foo {};
Foo foo;
s (foo);
这足够接近你想要的吗?@super-stag{}我能想到的唯一方法是使用预处理器黑客,这会带来各种不必要的副作用,因为预处理器不尊重范围。由于我不支持使用预处理器解决方案作为避免程序员键入的解决方案,如果有类似的情况,我只需更改函数的名称,例如改为get而不是operator,并使用调用语法s.get。或者,您可以这样调用:s Foo{};因此,您不需要显式的临时变量。在传递copy时需要一个可复制的可构造类型和一个构造起来可能比较昂贵/复杂的实例。@Jarod42是的,最好使用void运算符const t&Answer相应地更改。
template<class T> struct tag_t { };
template<class T> tag_t<T> tag{};
struct S {
template<class T>
T operator()( tag_t<T> );
} s;
s( tag<Foo> );
struct S {
template<class T>
void operator()(const T&) { }
} s;
struct Foo {};
Foo foo;
s (foo);