gpt4 book ai didi

c++ - 一个定义规则和模板类特化

转载 作者:太空狗 更新时间:2023-10-29 20:24:47 25 4
gpt4 key购买 nike

popular library 的作者决定执行the following design pattern :

// my_traits.hpp
#include <stdio.h>
#include <assert.h>

template<typename T>
struct my_traits {
static bool equals(const T& x, const T& y) {
printf("base\n");
return x == y;
}
};

template<typename T>
void my_assert(const T& x, const T& y) {
assert(my_traits<T>::equals(x, y));
}

现在假设库的使用如下:

// main.cpp
void my_test1();
void my_test2();

int main() {
my_test1();
my_test2();
return 0;
}

// my_test1.cpp
#include "my_traits.hpp"

void my_test1() {
my_assert(-1.0, -1.0);
}

//my_test2.cpp
#include "my_traits.hpp"

#ifdef _WIN32
#include <float.h>
#define isnan _isnan
#else
#include <math.h>
#endif

template<>
struct my_traits<double> {
static bool equals(const double& x, const double& y) {
printf("specialization\n");
return x == y || isnan(x) && isnan(y);
}
};

void my_test2() {
my_assert(-1.0, -1.0);
}

现在,

$ g++ main.cpp my_test1.cpp my_test2.cpp && ./a.out
base
base

鉴于

$ g++ main.cpp my_test2.cpp my_test1.cpp && ./a.out
specialization
specialization

当然,无论链接顺序如何,图书馆的用户都希望获得以下结果:

base
specialization

缺少特化或重载(内联)my_assert而不是 my_traits ,并且知道将相同的特化注入(inject)每个翻译单元,其中 my_traits.hpp被包含是 Not Acceptable (或可维护的),谁能想出另一个技巧来实现所需的行为而不修改 my_traits.hpp或专攻my_assert (或为 double 使用笨拙的包装类 :))?

最佳答案

§14.7.3 [temp.expl.spec]/p6(添加了重点):

If a template, a member template or a member of a class template is explicitly specialized then that specialization shall be declared before the first use of that specialization that would cause an implicit instantiation to take place, in every translation unit in which such a use occurs; no diagnostic is required. If the program does not provide a definition for an explicit specialization and either the specialization is used in a way that would cause an implicit instantiation to take place or the member is a virtual member function, the program is ill-formed, no diagnostic required.

关于c++ - 一个定义规则和模板类特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26303241/

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