gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:44:11 24 4
gpt4 key购买 nike

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

// 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com