如何根据模板参数制作代码生成
How to make code generation depending on template arguments?
如果模板参数不符合标准(某些值或类型(,我可以防止模板类的函数的产生吗?这可以通过使用C 代码和无预处理器指令来实现吗?
这种功能既不应在标头或体内可用。这种情况似乎有点人为,但我还没有找到解决方案。
示例类(简化 - 无构造函数等(:
myClass.h
template<int Dimension, typename TPixelType = float>
class MyClass
{
void DoSomething();
void DoAnotherThing(); // this function should only be available if Dimension > 2
}
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
}
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
}
在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!" );
// ...
}
在C 2a中,您可以使用requires
进行"丢弃"方法:
template<int Dimension, typename TPixelType = float>
class MyClass
{
void DoSomething();
void DoAnotherThing() requires (Dimension > 2);
};
一般建议:如果您有模板类,请在标题中实现全部并避免CPP文件。所有这些都变得简单得多。
如果模板参数不符合标准(某些值或类型(,我可以防止模板类的函数的产生吗?这可以通过使用C 代码和无预处理器指令来实现吗?
是,是的:搜索Sfinae。
在您的情况下(C 11和更新(
template <int Dimension, typename TPixelType = float>
class MyClass
{
public:
void DoSomething ()
{ }
template <int D = Dimension,
typename std::enable_if<(D > 2), bool>::type = true>
void DoAnotherThing()
{ }
};
现在仅在 D > 2
D
(默认情况下(等于 Dimension
时,才实现 DoAnotherThing()
方法。
不是一个完美的解决方案,因为可以"被劫持"阐明D
auto myclass0 = MyClass<2>();
myclass0.DoAnotherThing<5>(); // compile because D is 5
但是您可以防止此问题添加D
等于Dimension
template <int D = Dimension, // ..VVVVVVVVVVVVVVVV
typename std::enable_if<(D == Dimension)
&& (D > 2), bool>::type = true>
void DoAnotherThing()
{ }
so
auto myclass0 = MyClass<2>();
myclass0.DoAnotherThing<5>(); // doesn't compile anymore because 5 != 2
相关文章:
- C ++如何使用UTF8十六进制代码打印UTF8符号?
- C++逗号分隔的输入数组代码过早退出
- LLVM |如何实现逻辑非操作的 IR 代码生成
- C++基于输入参数的动态代码生成
- 在 c++ 的 10x10 数组中生成特定数量的多个随机字符
- 我的旋转数组代码给出了大数组大小的错误
- C++使用代码生成错误
- C++代码生成核心文件,就像 gdb >> gcore 一样
- 卤化物:X86汇编代码生成
- 如何将 MATLAB 图像处理库内置函数转换为 MATLAB 编码器代码生成不支持的 C++?
- 为什么我的代码为同一代码生成不同的值
- 我应该担心动态代码生成与用C++编写的其他模块不匹配吗?
- 用于"Ctrl + left arrow"和"Ctrl + right arrow"的八进制代码
- 企业架构师 - 单独的代码生成标头和实现
- C++ 代码生成和模板专用化
- 如何修复将传输到 java 的 2d 数组代码使用 JNI
- IBM Rhapsody c++ 代码生成 - 为什么总是在状态图周围放置一个活动状态
- 如何从 c++ 代码生成 arm64-v8a 64 位共享对象?
- 在语法文件上运行C 的ANTL4解析器显示错误33:缺少代码生成模板非局部trrefheader
- 技巧:使用宏填充数组值(代码生成)