如果模板参数不符合条件(某些值或类型),如何阻止生成模板化类的函数?可以通过使用c ++代码而不使用预处理程序指令来实现吗?
标题和正文中都不应提供这种功能。这种情况似乎有点人为,但我还没有找到解决方案。
示例类(简化-没有构造函数等):
MyClass.h
template<int Dimension, typename TPixelType = float>
class MyClass
{
void DoSomething();
void DoAnotherThing(); // this function should only be available if Dimension > 2
}
Run Code Online (Sandbox Code Playgroud)
MyClass.cxx
template< int Dimension, typename TPixelType> void MyClass::DoSomething()
{...}
// pseudocode: if Dimension <= 2 do not compile next function
template< int Dimension, typename TPixelType> void MyClass::DoAnotherThing()
{
MethodNotToBeCompiled(); // The function I don't want to be executed
}
Run Code Online (Sandbox Code Playgroud)
TestMyClass.cxx
int main()
{
auto myclass0 = MyClass<2>();
myclass0.DoSomething(); // OK
myclass0.DoAnotherThing(); // (wanted) error - function not available
auto myclass1 = MyClass<3>();
myclass1.DoSomething(); // OK
myclass1.DoAnotherThing(); // OK
}
Run Code Online (Sandbox Code Playgroud)
在C ++ XX中可能吗?还是除了预处理器指令外还有其他方法?
template <int Dimension, typename TPixelType> void MyClass::DoSomething() {/*...*/}
// if Dimension <= 2 do not compile next function
template <int Dimension, typename TPixelType>
void MyClass::DoAnotherThing()
{
static_assert(Dimension > 2, "function not available!" );
// ...
}
Run Code Online (Sandbox Code Playgroud)
在C ++ 2a中,您可以使用requires“丢弃”方法:
template<int Dimension, typename TPixelType = float>
class MyClass
{
void DoSomething();
void DoAnotherThing() requires (Dimension > 2);
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
87 次 |
| 最近记录: |