别名、模板化函数和专业化



我应该首先说,我对C++的了解非常有限。我对模板和专业化有一些了解,但我绝不是一个经验丰富的C++程序员。例如,我今天学到了";别名";其与";typedefs";这对我来说完全是个新闻。

我已经阅读了一些关于别名模板函数的内容,但我必须承认,我发现大多数示例都非常神秘,所以我提出了一个非常简单的用例,见下文。

#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<int24_t>而且还具有foo<int32_t>

创建别名(使用typedefusing(时,该别名与原始类型无法区分。不过,您可以考虑将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 2

最新更新