模板预编译 - C++模板按unsigned值编译
天蓬老师
天蓬老师 2017-04-17 13:44:48
0
1
648
#include <cstdio>

template<unsigned N>
int func() {
    if(N>100) {
        return 1;
    } else {
        static const char c = N; // g++: error, clang++: pass
        static const char s[1] = {N}; // both error
        printf("%c\n",c);
        return 0;
    }
}

int main() {
    func<1000>();
    return 0;
}

如图程序,为什么会有编译时错误呢?明明走了另一个分支啊!

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(1)
左手右手慢动作

In this case, if is not used, but specialization is used. The syntax that is logically equivalent to your code is:

template<unsigned N>
std::enable_if<(N <= 100), int>::type
func() {
    static const char c = N; // g++: error, clang++: pass
    static const char s[1] = {N}; // both error
    printf("%c\n",c);
    return 0;
}

template<unsigned N>
std::enable_if<(N > 100), int>::type
func() {
    return 1;
}

This will prevent the compiler from adding code containing syntax errors to the compilation during overload resolution.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!