任务:打印数字从1到1000,不使用任何循环或条件语句.不要只写1000次printf()或cout语句.
你会怎么用C或C++做到这一点?
我喜欢提供有用的错误/消息,我也想为我static_assert的.问题是,它们依赖于模板参数.通常情况下,由于引发的错误,这些参数会在途中或其他参数上显示,但它们要么模糊不清,要么不分组,因此它们有意义.例:
template<class T>
struct fake_dependency{
static bool const value = false;
};
template<class T, class Tag>
struct Foo{
Foo(){}
template<class OtherTag>
Foo(Foo<T, OtherTag> const&){
static_assert(fake_dependency<T>::value, "Cannot create Foo<T,Tag> from Foo<T,OtherTag>.");
}
};
int main(){
Foo<int, struct TagA> fA;
Foo<int, struct TagB> fB(fA);
}
Run Code Online (Sandbox Code Playgroud)
MSVC上的输出:
src\main.cpp(74): error C2338: Cannot create Foo<T,Tag> from Foo<T,OtherTag>.
src\main.cpp(84) : see reference to function template instantiation 'Foo<T,Tag>::Foo<main::TagA>(const Foo<T,main::TagA> &)' being compiled
with
[
T=int,
Tag=main::TagB
]
Run Code Online (Sandbox Code Playgroud)
函数模板本身提到了一个标记,下面是类模板.不太好.让我们看看海湾合作委员会的成果:
prog.cpp: In constructor 'Foo<T, Tag>::Foo(const …Run Code Online (Sandbox Code Playgroud) 我正在编写一个非常简单的模板类,使用元编程在编译时计算总和,如下所示:
#include <iostream>
using namespace std;
template<int N>
class Sum
{
public:
enum {value = N + Sum<N-1>::value };
};
template<>
class Sum<0>
{
public:
enum {value = 0};
};
int main()
{
cout << Sum<501>::value << endl;
}
Run Code Online (Sandbox Code Playgroud)
有趣的是:
当谈到Sum <501>时,编译失败了:
sum.cpp:9:从
Sum<500>' sum.cpp:9: instantiated fromSum <501>'sum.cpp:22实例化:从这里实例化sum.cpp:9:错误:不完整的类型
Sum<1>' used in nested name specifier sum.cpp:9: error: enumerator value for值'不是整数常量
Sum <501>将报告Sum <1>的错误,Sum <502>将报告Sum <2>的错误,差值始终为2,在我看来编译器的限制资源为500.
对此有何想法?他们是打破这种限制的一种方式吗?
谢谢.
编辑:
谢谢大家,重点不是关于算法,而是编译器的限制 - 我知道有一个简单的方法来获得总和:)
EDIT2:
sum.cpp:9:14:错误:模板实例化深度超过1024的最大值(使用-ftemplate-depth …
我正在尝试做一些模板元编程,我发现需要"提取"某种类型的某种结构的特化的最高指数.
例如,如果我有一些类型:
struct A
{
template<unsigned int> struct D;
template<> struct D<0> { };
};
struct B
{
template<unsigned int> struct D;
template<> struct D<0> { };
template<> struct D<1> { };
};
struct C
{
template<unsigned int> struct D;
template<> struct D<0> { };
template<> struct D<1> { };
template<> struct D<2> { };
};
Run Code Online (Sandbox Code Playgroud)
那我怎么能写一个像这样的元函数:
template<class T>
struct highest_index
{
typedef ??? type;
// could also be: static size_t const index = ???;
};
Run Code Online (Sandbox Code Playgroud)
给我D一个在上面的任意结构中专门的最高索引,而不 …
c++ templates sfinae template-specialization template-meta-programming
在写完这个问题的答案后,在编译时显示解决方案并出现错误,我想知道是否有可能得到警告并完成编译(正如问题中实际指定的那样).
虽然诊断通常是依赖于编译器的,但对于某些代码来说,很明显会触发错误(例如访问不存在的成员或尝试实例化不完整类型的对象).
但是,警告不能说同样的,因为这些编译器之间的差别很大.即使假设用GCC触发的警告也会被Clang触发是合理的,但对于Visual C++来说也是如此.
问题:
在所有三个提到的编译器中,将始终触发哪些警告(如果有)?
/W3在VC++和-WallGCC&Clang上可以假设.
请注意,这不仅对该问题有用,而且对于触发用户定义消息的警告也很有用.