首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >别名、模板函数和专门化

别名、模板函数和专门化
EN

Stack Overflow用户
提问于 2020-12-15 21:57:20
回答 1查看 61关注 0票数 0

首先,我应该说,我对C++的了解非常有限。我对模板和专业化有一定的了解,但我绝不是一个经验丰富的C++程序员。例如,我今天学到了“别名”,它与“类型防御”不完全一样,这对我来说完全是新闻。

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

代码语言:javascript
复制
#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实现?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-15 22:22:09

当您创建了别名(使用typedefusing)时,该别名与原始类型无法区分。不过,您可以考虑让int24_t成为一个enum

示例:

代码语言:javascript
复制
#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);
}

输出

代码语言:javascript
复制
int24_t 1
int32_t 2
base 3
int24_t 2
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65314268

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档