【发布时间】:2019-01-24 09:09:27
【问题描述】:
是否有可能在不同的地方将类方法的定义和声明与模板参数(特别是在使用constexpr 函数时使用)分开?因为“模板参数”不是像模板函数的显式特化吗?
或者这种情况与已经讨论好的话题纠缠不清: Why can’t I separate the definition of my templates class from its declaration and put it inside a .cpp file?
Why can templates only be implemented in the header file?
例如: 头文件“someHeader.h”
#include <iostream>
#pragma once
class cc
{
public:
cc()=default;
~cc()=default;
template<uint32 f_val2Check_u32>
constexpr uint32 isPowerOf2();
private:
};
然后是 *.cpp 文件:
// cpp-file
#include "someHeader.h"
template<uint32 val>
constexpr uint32 cc::isPowerOf2()
{
return ((val&(val-1))==0);
}
【问题讨论】:
-
基本上没有。原因是调用代码实际上是通过填充它进行调用的类型来生成函数体。所以编译器需要看到模板主体,而不仅仅是签名。 (当然会有办法解决这个问题,但这是 20 多年前设计规则时的动机)。
标签: c++ c++11 templates c++14 constexpr