首先,我应该说,我对C++的了解非常有限。我对模板和专业化有一定的了解,但我绝不是一个经验丰富的C++程序员。例如,我今天学到了“别名”,它与“类型防御”不完全一样,这对我来说完全是新闻。
我已经阅读了一些关于别名模板函数的内容,但是我不得不承认,我发现大多数例子都很神秘,所以我想出了一个非常简单的用例,见下文。
#include <iostream>
// A fictitious 24-bit type, that can be manipulated like any other type but can be distinguished from the underlying 32-bit type
using int24_t = int32_t;
template<typename T>
void foo(T x)
{
std::cout << "x = " << x << std::endl;
}
template<>
void foo<int24_t>(int24_t x)
{
std::cout << "24-bit specialization - x = " << x << std::endl;
}
int main(void)
{
foo<int16_t>(0);
foo<int24_t>(1);
foo<int32_t>(2); // Indistinguishable from 24-bit
}是否有可能做我想做的事,即有一个foo的专门化,但也有一个通用的foo实现?
发布于 2020-12-15 22:22:09
当您创建了别名(使用typedef或using)时,该别名与原始类型无法区分。不过,您可以考虑让int24_t成为一个enum。
示例:
#include <cstdint>
#include <iostream>
enum int24_t : std::int32_t {};
template<typename T>
void foo(T v) {
std::cout << "base " << v << '\n';
}
template<>
void foo<std::int32_t>(std::int32_t v) {
std::cout << "int32_t " << v << '\n';
}
template<>
void foo<int24_t>(int24_t v) {
std::cout << "int24_t " << v << '\n';
}
int main() {
int24_t a{1};
std::int32_t b{2};
unsigned c{3};
foo(a);
foo(b);
foo(c);
a = static_cast<int24_t>(b); // needed to assign an int32_t to the enum type
foo(a);
}输出
int24_t 1
int32_t 2
base 3
int24_t 2https://stackoverflow.com/questions/65314268
复制相似问题