在以下C++代码中,函数fun1的参数中的模板占位符和函数ret1的返回类型中的模板占位符不编译:
template <typename T = int>
class type {
T data;
};
void fun1(type arg); // Error: template placeholder not permitted in this context
void fun2(type<> arg); // Ok
void fun3(type<int> arg); // Ok
type ret1(); // E
我想用c++17自动推断一个类‘(带有默认的模板参数)。有人知道这是否可能吗?以下代码试图说明这一点:
#include <vector>
template <typename T = int>
struct A{
using Vec = std::vector<T>;
};
int main() {
A a{}; // works with c++ 17
A<int>::Vec vec2{}; //works
A::Vec vec{}; //does not seem to work with c++ 17.
考虑下面的C++程序
#include<map>
#include<iostream>
int main() {
int a = 5, b = 7;
auto pair = std::make_pair<int, int>(a,b);
return 0;
}
使用VC11并在中使用不同的错误,尽管它似乎是相关的,并且VC11错误消息更有意义
You cannot bind an lvalue to an rvalue
我从这次失败中了解到
VC11和我猜想gcc-4.7.2只有一个std::make_pair mak
我尝试用默认模板参数编写这个函数:
template<typename A, typename B>
void func(int i1, int i2, A a, B b = 123){
...
}
在我看来,我可以这样称呼它:func(1, 2, 3)和编译器应该从默认值中推断出B类型为int,但我得到了no instance of overloaded function。
在这种情况下,是否不正确的C++结构和编译器不能推断类型?
为什么以下示例中的&&参数类型不表现为所谓的“通用引用”,即使它似乎处于“推导的上下文”中,而是被解释为r值:
auto main() -> int {
using MyFn = void (*)(int &);
MyFn special = [](auto && thing) {}; // compile error, deduced as int && rather than int&
return 0;
}
而下面这些,我希望它是等价的,是否有效呢?
temp
ML如何在以下函数定义中执行类型推断:
let add a b = a + b
它是否像C++模板一样,在模板实例化之前不执行类型检查,在模板实例化之后,如果类型支持必要的操作,函数就会工作,否则就会抛出编译错误?
例如,下面的函数模板
template <typename NumType>
NumType add(NumType a, NumType b) {
return a + b;
}
将适用于
add<int>(23, 11);
但不适用于
add<ostream>(cout, fout);
我猜测的是正确的还是ML类型推断的工作方式不同?
附
在C++中,我有一个关于特定模板友谊的问题。在C++ Primer一书中,具体的模板友谊如下所示:
template <class T> class Foo3;
template <class T> void templ_fcn3(const T&);
template <class Type> class Bar {
// each instantiation of Bar grants access to the
// version of Foo3 or templ_fcn3 instantiated with the
我正在尝试了解如何使用C++(11) <type_traits>。
下面是我的简单测试程序
#include <type_traits>
template<class U, class S>
inline U add(typename std::enable_if<std::is_unsigned<U>::value,U>::type a,
typename std::enable_if<std::is_signed <S>::value,S>::type b)
{
ret
我正在努力理解我今天看到的下面的代码。我已经试图找到一个相关的问题,但是由于我不知道C++的这个特性被称为什么,所以很难找到相关的帖子。关于正确的搜索词的提示可能已经对我有帮助了。
struct A
{ int x; };
struct B
{ B(A a) {}; };
int main()
{
B b{ { 5 } }; // works, seems to create a struct A from {5} and pass it to B's constructor
std::make_unique<B>({ 5 }); // doesn
是否有一种方法可以编写通用函数来清除C++中任何具有给定项类型的堆栈?我目前正在编写一个使用字符串堆栈和整数堆栈的程序,但我不知道如何将堆栈作为一个参数传递,该参数决定运行时它包含哪些数据,以及如何删除它。我的想法是:
void clearStack(stack &s) {
while(!s.empty())
s.pop();
}
但是,这说明了argument list for class template "std::stack" is missing。C++是否有一种将堆栈作为参数传递而不需要值类型的方法?
*注:这只是练习而已。环顾四周后
例如,有没有一种方法可以获取模板类的类型
//i have template function
template<typename T>
IData* createData();
//a template class instance
std::vector<int> a;
//using type of this instance in another template
//part in quotation mark is imaginary of course :D
IData* newData = createData<"typeOf(a)