使C ++无法在模板函数的特定实例上编译 [英] Make C++ fail compilation on specific instantiation of template function

查看:59
本文介绍了使C ++无法在模板函数的特定实例上编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从事一个具有模板功能的项目:

I'm working on a project which has an template function as so:

template <class T> 
T foo<T>(T val) { return someFunc(val); }

template <>
bool foo<bool>(bool val) { return otherFunc(val); };

现在,我有一个课程 Bar ,我不想接受输入。实际上,我希望它生成易于发现的编译错误。问题是如果我这样做:

Now, I have a class Bar, which I don't want to accept as input. In fact, I want it to generate an easy to spot compile error. The problem is that if I do this:

template <>
Bar foo<Bar>(Bar val) { static_assert(false,"uh oh..."); }

每次编译都会失败。我找到了 https://stackoverflow.com/a/3926854/7673414 ,这表示我需要参考模板类型,否则将始终执行静态断言。问题是我这里没有模板类型。如果我这样做:

It fails on every compile. I found https://stackoverflow.com/a/3926854/7673414, which says that I need to make reference to the template type, otherwise the static assert always takes place. The problem is I don't have a template type here. If I do:

template< typename T >
struct always_false { 
    enum { value = false };  
};

template <>
Bar foo<Bar>(Bar val) { static_assert(always_false<Bar>::value,"uh oh..."); }

然后它也总是无法编译。有没有一种方法可以确保类型为 Bar 的模板的实例化始终导致编译错误?

then it also always fails compiling. Is there a way to ensure that an instantiation of the template with type Bar always causes a compile error?

推荐答案

由于 foo 是完全专业化的,因此它将始终被编译,而静态断言将始终被调用。

Since foo is a complete specialization, it will always get compiled, and the static assert will always get called.

但是,有一个更简便的方法

template <>
Bar foo<Bar>(Bar val) = delete;

这将表示该特定版本已删除,无法调用。

This will say that this specific version is deleted, and cannot be called.

这篇关于使C ++无法在模板函数的特定实例上编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆