gpt4 book ai didi

c++ - 隐藏函数模板,声明特化

转载 作者:搜寻专家 更新时间:2023-10-31 00:23:24 25 4
gpt4 key购买 nike

这是 C++ templates: prevent instantiation of base template 的跟进

我使用模板来实现函数重载,而无需隐式类型转换的困惑:声明函数模板,定义所需的特化(重载)。一切都很好,除了错误的代码在链接阶段之前不会产生错误:

lib.hpp:

template<class T> T f(T v);

lib.cpp:

#include "lib.hpp"

template<> long f(long v) { return -v; }
template<> bool f(bool v) { return !v; }

主要.cpp:

#include <iostream>
#include "lib.hpp"

int main()
{
std::cout
<< f(123L) << ", "
<< f(true) << ", "
<< f(234) << "\n"
;
}

gcc 输出:

c++ -O2 -pipe -c main.cpp
c++ -O2 -pipe -c lib.cpp
c++ main.o lib.o -o main
main.o(.text+0x94): In function `main':
: undefined reference to `int get<int>(int)'

我想让它在编译 main.cpp 时失败。我能否以某种方式仅声明实际实现的特化?

我有哪些选择?目标是C++03,我主要对gcc-4.x和VC9感兴趣。

最佳答案

即使您不将它放在单独的文件中,它似乎也会产生链接器错误。

但是,要为其他实例化生成编译器错误,请实现该函数并使用编译时断言,例如

#include <boost/static_assert.hpp>

template <class T> T f(T)
{
//assert some type-dependent "always-false" condition,
//so it won't be triggered unless this function is instantiated
BOOST_STATIC_ASSERT(sizeof(T) == 0 && "Only long or bool are available");
}

template<> long f(long v) { return -v; }
template<> bool f(bool v) { return !v; }

int main()
{
//f(100);
f(100L);
f(false);
}

对于一般信息,C++0x 有一种更优雅的方式来处理它:

template <class T> T f(T) = delete;

template<> long f(long v) { return -v; }
template<> bool f(bool v) { return !v; }

关于c++ - 隐藏函数模板,声明特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2155491/

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