c++ - 检查子类型时特化方法模板

标签 c++ templates variadic-templates sfinae template-specialization

在检查某些子类型是否存在的同时为方法专门化模板的语法是什么?

// Syntax works fine for functions
template<class T, class... Assertions> void my_function();

template <class list_t, class list_t::value_type>
void my_function() { }

// Doesn't work for methods
class MyClass {
    template<class T, class... Assertions> void my_method();
};

// Commenting out the next two lines results in successful compile
template <class list_t, class list_t::value_type>
void MyClass::my_method() { }

int main() { }

Clang 给我:

out-of-line definition of 'my_method' does not match any declaration in 'MyClass'

最佳答案

您在这里既没有特化模板方法也没有特化函数。您只是在重载自由模板函数并试图以一种奇怪的方式重载该方法。为了让它工作你应该使用标签分派(dispatch)(因为部分函数模板特化在 C++ 中是不可能的)或者 constexpr if 如果你的编译器支持 C++17

关于c++ - 检查子类型时特化方法模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52549479/

相关文章:

C++11 使用可变模板参数创建编译时 bool 表达式

c++ - 如果不更改全局信号处理程序,是否可以强制 OpenSSL 不生成 SIGPIPE?

python - 通过boost python从python中提取常量值

c++ - 使用 Init() 进行内存分配是否比构造函数更好?

c++ - 条件 (SFINAE) 覆盖

c++ - 是否可以为模板提供可变参数列表或根据提供的参数列表自动生成规范

c++ - 声明一个没有参数的模板结构

c++ - 如何使用 std::enable_if 有条件地选择可变参数构造函数?

c++ - 参数包函数参数可以默认吗?

c++ - 如何使用 vlc-qt 从视频中获取帧