以下是我尝试做的一个最小代码示例,它能够运行,但不符合我的期望:
#include <string>
#include <type_traits>
#include <iostream>
struct string_tag {
using R=const std::string;
};
struct int_tag {
using R=const int;
};
template <bool TS>
class Wibble {
public:
template<typename TAG>
typename TAG::R getValue(TAG);
};
template <bool TS>
template <typename TAG>
typename TAG::R Wibble<TS>::getValue(TAG) {
if constexpr (std::is_same<TAG, string_tag>::value) {
return "hello";
}
if constexpr (std::is_same<TAG, int_tag>::value) {
return 42;
}
}
// instantiate classes
template class Wibble<true>;
template class Wibble<false>;
int main () {
Wibble<true> tw;
Wibble<false> fw;
std::cout << "tw string: " << tw.getValue(string_tag{}) << std::endl;
std::cout << "tw int: " << tw.getValue(int_tag{}) << std::endl;
std::cout << "fw string: " <<fw.getValue(string_tag{}) << std::endl;
std::cout << "fw int: " << fw.getValue(int_tag{}) << std::endl;
}
我想要更改的部分是所有constexpr
逻辑的函数模板定义看起来很丑陋。我希望能够单独定义TAG
中的不同特化,但是这样做会导致redefinition of ...
错误。
下面这样的语法会很好:
template<bool TS>
template<>
string_tag::R Wibble<TS>::getValue(string_tag) {
return "hello";
}
但电脑说“不行”。
概念
。你准备好使用C++20了吗?回复:“计算机说‘不’”+1 - Ted LyngmogetValue()
不依赖于TS
参数,应该将其实现为一个单独的模板函数,可以正常地进行特化。类模板仍然可以定义自己的getValue()
方法,仅仅调用“真正”的getValue()
。我期望现代 C++ 编译器能够优化掉额外的函数调用。 - Sam Varshavchik